<template>
	<div class="apiGroupBox">
		<el-card class="card-left">
			<template #header>
				<div class="card-header">
					<el-button v-auth="'sys:platform:classify:save'" :icon="Plus" type="primary" @click="addType">新建分类</el-button>
					<el-button v-auth="'sys:platform:save'" :icon="Plus" type="primary" @click="addPlatForm">新建平台</el-button>
				</div>
			</template>
			<el-scrollbar scroll-y class="leftBox">
				<el-tree :data="dataSource" node-key="id" default-expand-all highlight-current :expand-on-click-node="false" @node-click="handleNodeClick">
					<template #default="{ node, data }">
						<span class="custom-tree-node">
							<!-- <span>{{ node.label }}</span> -->
							<el-tooltip v-if="countLength(node.label) > 20" effect="dark" :content="node.label" placement="top-start">
								<el-text style="width: 7.5em" truncated>{{ node.label }}</el-text>
							</el-tooltip>
							<span v-else>{{ node.label }}</span>
							<span>
								<a v-auth="'sys:platform:classify:update'" style="margin-left: 8px; color: blue" @click="edit(data)">
									<el-icon><Edit /></el-icon>
								</a>
								<a v-auth="'sys:platform:classify:delete'" style="margin-left: 8px; color: red" @click="handleDelete(data)">
									<el-icon><Delete /></el-icon>
								</a>
							</span>
						</span>
					</template>
				</el-tree>
			</el-scrollbar>
		</el-card>
		<el-card class="card-right">
			<template #header>
				<div class="card-header">
					<el-button v-auth="'sys:platform:classify:update'" type="primary" @click="save">保存</el-button>
				</div>
			</template>
			<el-scrollbar scroll-y class="rightBox">
				<!-- <el-tree
					ref="typeTreeRef"
					:data="menuSource"
					node-key="id"
					show-checkbox
					default-expand-all
					:expand-on-click-node="false"
					:props="defaultProps"
				>
					<template #default="{ node, data }">
						<span class="custom-tree-node">
							<span>{{ data.name }}</span>
						</span>
					</template>
				</el-tree> -->
				<form-tree
					v-model="newArr"
					:data="menuSource"
					:props="{ label: 'name', children: 'children' }"
					:node-key="'id'"
					style="width: 100%"
					show-checkbox
				>
				</form-tree>
			</el-scrollbar>
		</el-card>
		<el-dialog v-model="typeDialog.visible" :title="typeDialog.title" :before-close="dialogClose">
			<Form ref="typeFormRef" :form-state="typeFormState" :form-data="typeFormData"></Form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="typeDialog.visible = false">取 消</el-button>
					<el-button type="primary" :loading="typeDialog.loading" @click="typeSave">保 存</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="platFormDialog.visible" :title="platFormDialog.title" :before-close="dialogClose">
			<Form ref="platFormRef" :form-state="platFormState" :form-data="platFormData"></Form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="platFormDialog.visible = false">取 消</el-button>
					<el-button type="primary" :loading="platFormDialog.loading" @click="platSave">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import Form from '@/components/Form/index.vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import store from '@/store'
import {
	platformClassifySave,
	platformClassifyUpdate,
	platformClassifyDelete,
	platformList,
	platformSave,
	platformUpdate,
	platformDelete,
	platformConnect,
	platformMenuUseList
} from '@/api/sys/platform'
import service from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import { transMap } from '@/utils/tool'
import formTree from '@/components/Form/form-tree.vue'

const countLength = str => {
	const l = str.replace(/[\\u4E00-\\u9FFF]/g, '').length
	return str.length + l
}

interface Tree {
	id: number
	label: string
	children?: Tree[]
}
const defaultProps = {
	children: 'children',
	label: 'label'
}
const typeTreeRef = ref()
const typeFormRef: any = ref(null)
const typeDialog = ref({
	title: '新建分类',
	visible: false,
	loading: false
})
const typeFormState = ref({
	classifyName: '',
	sort: 0,
	comment: ''
})
const oldtypeState = ref('')
const typeFormData = ref([
	{
		title: '分类名称',
		dataIndex: 'classifyName',
		type: 'input',
		rules: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
	},
	{
		title: '排序',
		dataIndex: 'sort',
		type: 'inputNumber',
		rules: [{ required: true }]
	},
	{
		title: '描述',
		dataIndex: 'comment',
		type: 'input'
		// rules: [{ required: true, message: '请输入描述', trigger: 'blur' }]
	}
])
const platFormRef: any = ref(null)
const platFormDialog = ref({
	title: '新建平台',
	visible: false,
	loading: false
})
const platFormState = ref({
	classifyId: '',
	platformName: '',
	systemType: '',
	networkType: '',
	url: '',
	api: '',
	backgroundImage: '',
	sort: 0,
	notes: ''
})
const oldplatFormState = ref('')
const platFormData = ref([
	{
		title: '所属分类',
		dataIndex: 'classifyId',
		type: 'select',
		data: [],
		rules: [{ required: true, message: '请选择所属分类', trigger: 'change' }]
	},
	{
		title: '平台名称',
		dataIndex: 'platformName',
		type: 'input',
		rules: [{ required: true, message: '请输入平台名称', trigger: 'blur' }]
	},
	{
		title: '系统类型',
		dataIndex: 'systemType',
		type: 'select',
		data: [
			{
				value: 'PC',
				label: 'PC'
			},
			{
				value: '手机',
				label: '手机'
			},
			{
				value: '通用',
				label: '通用'
			}
		],
		rules: [{ message: '请选择系统类型', trigger: 'change' }]
	},
	{
		title: '网络类型',
		dataIndex: 'networkType',
		type: 'select',
		data: [
			{
				value: '公网',
				label: '公网'
			},
			{
				value: '内网',
				label: '内网'
			},
			{
				value: '专网',
				label: '专网'
			}
		],
		rules: [{ message: '请输入网络类型', trigger: 'change' }]
	},
	{
		title: 'URL',
		dataIndex: 'url',
		type: 'input',
		rules: [{ required: true, message: '请输入系统URL', trigger: 'blur' }]
	},
	{
		title: '推送API',
		dataIndex: 'api',
		type: 'input',
		rules: [{ message: '请输入系统API', trigger: 'blur' }]
	},
	{
		title: '背景图片',
		dataIndex: 'backgroundImage',
		type: 'uploadSys',
		rules: [{ message: '请上传平台背景图' }]
	},
	{
		title: '排序',
		dataIndex: 'sort',
		type: 'inputNumber',
		rules: [{ required: true }]
	},
	{
		title: '备注',
		dataIndex: 'notes',
		type: 'input',
		rules: [{ message: '请输入系统备注', trigger: 'blur' }]
	}
])
const dataSource = ref([])
const menuSource = ref([])
const menuList = ref([])
const selected = ref({})

onMounted(() => {
	init()
})

const init = () => {
	let param = {
		// orgCode: store.userStore.user.orgId || 1
	}
	platformList(param).then((res: any) => {
		dataSource.value = res.data
		const item = platFormData.value.find(v => {
			return v.dataIndex === 'classifyId'
		})
		item.data = res.data
		item.data.forEach(i => {
			i.value = i.id
		})
	})
}

let newArr = ref([])
let oldArr = ref([])

// 去除跟添加父节点选中
const addRemove = (arr: any, type: string) => {
	let menus = menuList.value.filter(val => {
		return arr.indexOf(val.id) !== -1
	})
	if (type == 'remove') {
		menus.forEach((item, index) => {
			if (item.children) {
				menus.splice(index, 1)
			}
		})
		return menus.map(item => item.id)
	} else {
		menuList.value.forEach(item => {
			menus.forEach(val => {
				if (item.id == val.pid) {
					if (!menus.includes(item)) {
						menus.push(item)
					}
				}
			})
		})
		return menus.map(item => item.id)
	}
}

const getMenuList = () => {
	let param = {
		platformId: selected.value.id,
		type: '0'
	}
	platformMenuUseList(param).then((res: any) => {
		const data = transMap(res.data[0])

		menuList.value = res.data[0]
		menuSource.value = data

		newArr.value = res.data[0].reduce((p, c) => {
			if (c.userMenuId || c.userMenuId === 0) {
				return [...p, c.id]
			} else {
				return [...p]
			}
		}, [])
		oldArr.value = newArr.value
		newArr.value = addRemove(newArr.value, 'remove')
	})
}

const handleNodeClick = (data: Tree) => {
	selected.value = data
	if (!selected.value.hasOwnProperty('comment')) {
		getMenuList()
	}
}

const typeSave = async () => {
	try {
		typeDialog.value.loading = true
		await typeFormRef.value.submit()
		let params = {
			...typeFormState.value,
			orgCode: store.userStore.user.orgId || 1,
			deleted: 0
		}
		let res
		if (typeDialog.value.title === '新建分类') {
			res = await platformClassifySave(params)
		} else {
			res = await platformClassifyUpdate(params)
		}
		if (res.code == 0) {
			ElMessage({
				message: '保存成功',
				type: 'success'
			})
			typeDialog.value.loading = false
			typeDialog.value.visible = false
			init()
			selected.value = {}
		} else {
			ElMessage({
				message: res.msg,
				type: 'error'
			})
		}
	} catch (e) {
		typeDialog.value.loading = false
		console.log(e)
	}
}
const platSave = async () => {
	try {
		platFormDialog.value.loading = true
		// if (!platFormState.value.backgroundImage) {
		// 	platFormState.value.backgroundImage = 'http://192.168.100.56:9000/platform/20231214/getawayBg_57397.png'
		// }
		await platFormRef.value.submit()
		let params = {
			...platFormState.value,
			orgCode: store.userStore.user.orgId || 1,
			deleted: 0
		}

		let res
		if (platFormDialog.value.title === '新建平台') {
			res = await platformSave(params)
		} else {
			res = await platformUpdate(params)
		}
		if (res.code == 0) {
			ElMessage({
				message: '保存成功',
				type: 'success'
			})
			platFormDialog.value.loading = false
			platFormDialog.value.visible = false
			init()
			selected.value = {}
		} else {
			ElMessage({
				message: res.msg,
				type: 'error'
			})
		}
	} catch (e) {
		platFormDialog.value.loading = false
		console.log(e)
	}
}
// 新建分类
const addType = () => {
	typeDialog.value.title = '新建分类'
	dialogReset()
	typeDialog.value.visible = true
}
// 新建平台判断
const addPlatForm = () => {
	if (JSON.stringify(selected.value) == '{}' || !selected.value.hasOwnProperty('comment')) {
		ElMessage({
			type: 'error',
			message: '请先选择分类!'
		})
	} else {
		platFormDialog.value.title = '新建平台'
		platformReset()
		platFormDialog.value.visible = true
	}
}
// 删除
const handleDelete = (item: any) => {
	ElMessageBox.confirm('此操作确认删除后不可恢复，请谨慎操作！', `确认删除吗？`, {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			const params = {
				id: item.id
			}
			if (item.hasOwnProperty('comment')) {
				// 通过comment字段判断是否为分类
				platformClassifyDelete(params).then((res: any) => {
					if (res.code == 0) {
						init()
						ElMessage({
							type: 'success',
							message: '删除成功'
						})
					} else {
						ElMessage({
							type: 'error',
							message: res.message
						})
					}
				})
			} else {
				const platformParam = {
					id: item.id,
					classifyId: item.classifyId
				}
				platformDelete(platformParam).then((res: any) => {
					if (res.code == 0) {
						init()
						ElMessage({
							type: 'success',
							message: '删除成功'
						})
					} else {
						ElMessage({
							type: 'error',
							message: res.message
						})
					}
				})
			}
			selected.value = {}
		})
		.catch(() => {
			console.log('取消')
		})
}

const dialogReset = (item: any) => {
	const obj = {
		classifyName: '',
		sort: 0,
		comment: ''
	}
	if (item) {
		oldtypeState.value = item.INVALID_FLAG
		typeFormState.value = { ...obj, ...item }
	} else {
		oldtypeState.value = ''
		typeFormState.value = { ...obj }
	}
}
const platformReset = (item: any) => {
	const obj = {
		classifyId: '',
		platformName: '',
		systemType: '',
		networkType: '',
		url: '',
		api: '',
		sort: 0,
		notes: ''
	}
	if (item) {
		oldplatFormState.value = item.INVALID_FLAG
		platFormState.value = { ...obj, ...item }
	} else {
		oldplatFormState.value = ''
		platFormState.value = { ...obj, classifyId: selected.value.id }
	}
}

const dialogClose = (done: Function) => {
	done()
}
// 编辑
const edit = (data: any) => {
	if (data.hasOwnProperty('comment')) {
		typeDialog.value.title = '编辑分类'
		let obj: any = {}
		for (let key in typeFormState.value) {
			obj[key] = data[key]
			obj['classifyName'] = data['label']
			obj['id'] = data['id']
		}
		dialogReset(obj)
		typeDialog.value.visible = true
	} else {
		platFormDialog.value.title = '编辑平台'
		let obj: any = {}
		for (let key in platFormState.value) {
			obj[key] = data[key]
			obj['platformName'] = data['label']
			obj['id'] = data['id']
		}

		//if (obj.backgroundImage == 'http://192.168.100.56:9000/platform/20231214/getawayBg_57397.png') {
		//	obj.backgroundImage = ''
		//}
		platformReset(obj)
		platFormDialog.value.visible = true
	}
}
// 平台绑定
const platformBind = () => {
	let param = {
		platformId: selected.value.id,
		menuIdList: newArr.value
	}
	platformConnect(param).then((res: any) => {
		if (res.code == 0) {
			ElMessage({
				message: '保存成功',
				type: 'success'
			})
			init()
			menuSource.value = []
			selected.value = {}
		}
	})
}
// 保存
const save = () => {
	if (JSON.stringify(selected.value) == '{}' || selected.value.hasOwnProperty('comment')) {
		ElMessage({
			type: 'error',
			message: '请先选择平台!'
		})
	} else {
		// let menus = typeTreeRef.value!.getCheckedNodes(false, false).map(item => {
		// 	return item.id
		// })
		let newChose = addRemove(newArr.value, 'add')
		if (oldArr.value.length > newChose.length) {
			return new Promise((resolve, reject) => {
				// 获取取消选中值
				let lists = oldArr.value.filter(val => {
					return newChose.indexOf(val) === -1
				})
				let menus = menuList.value.filter(val => {
					return lists.indexOf(val.id) !== -1
				})
				let newMenus = []
				menus.forEach(val => {
					menus.forEach(item => {
						if (val.pid == item.id) {
							if (!newMenus.includes(item)) {
								newMenus.push(item)
							}
						}
					})
				})
				lists = []
				if (newMenus.length == menus.length) {
					menus.forEach(item => {
						lists.push(item.id)
					})
				} else {
					let diff = menus.filter(item => !newMenus.includes(item))
					diff.forEach(item => {
						lists.push(item.id)
					})
				}
				// 去除父节点的取消选择
				const params = {
					menu_id: lists,
					platformIdLists: [selected.value.id]
				}
				service
					.post('/sys/platform/platformRoleMenuList', params)
					.then(res => {
						if (res.data) {
							ElMessageBox.confirm(`系统检测到平台下的菜单或功能被取消，此操作会影响涉其关联机构下的角色所绑定的用户权限，此功能暂未开放`, '警告', {
								confirmButtonText: '确定',
								showCancelButton: false,
								type: 'warning'
							})
								.then(() => {
									resolve()
								})
								.catch(() => {
									reject()
								})
						} else {
							platformBind()
						}
					})
					.catch(e => {
						reject(e.msg)
					})
			})
		} else {
			platformBind()
		}
	}
}
</script>

<style lang="scss" scoped>
.card-left {
	min-width: calc(228px + #{var(--el-card-padding)} * 2);
	height: 100%;
}
.card-right {
	height: 100%;
	position: relative;
	::v-deep(.el-card__body) {
		height: calc(100% - 65px - #{var(--el-card-padding)} * 2);
		position: relative;
	}
}
.apiGroupBox {
	position: absolute;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
	display: flex;
	.el-card:first-child {
		width: 20%;
	}
	.el-card:nth-child(2) {
		width: 75%;
		margin-left: 15px;
	}
}
::v-deep(.el-card__header) {
	padding-top: 8px;
	padding-bottom: 8px;
}
.card-header {
	button:first-child {
		margin-right: 12px;
	}
	button {
		margin: 8px 0;
	}
	display: flex;
	flex-direction: row;
	flex-wrap: nowrap;
	align-items: center;
}
/* 左侧布局 */
.leftBox {
	height: calc(100vh - 250px);
	overflow-y: auto;
}
/* 右侧布局 */
.rightBox {
	// height: calc(100vh - 300px);
	height: 100%;
	overflow: auto;
}
.custom-tree-node {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 8px;
}
</style>
